package com.hissy.common.office.exporter;

import java.io.ByteArrayOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * Created by zhangyanfei on 2019/10/8.
 *
 * @author zhangyanfei
 * @date 2019/10/08
 */
public class XlsDataExporter implements DataExporter {
    HSSFWorkbook workbook;
    Sheet sheet;
    HSSFCellStyle cellStyle;
    Row row;
    int[] widths = null;

    @Override
    public String getExtension() {
        return "xls";
    }

    @Override
    public void writeRow(String[] values) throws Exception {
        row = sheet.createRow(row == null ? 0 : sheet.getLastRowNum() + 1);
        for (int i = 0; i < values.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            RichTextString richTextString = new HSSFRichTextString(values[i]);
            cell.setCellValue(richTextString);
            cell.setCellStyle(cellStyle);
        }
        calculateWidth(values);
    }

    private void calculateWidth(String[] values) {
        if (widths == null) {
            widths = new int[values.length];
            for (int index = 0; index < widths.length; ++index) {
                widths[index] = 200;
            }
        }

        // 计算宽度
        for (int index = 0; index < widths.length; ++index) {
            int oldWidth = widths[index];
            int newWidth = values[index].length() * 256 + (values[index].getBytes().length - values[index].length()) * 128;
            if (newWidth > oldWidth) {
                widths[index] = newWidth;
            }
            if (widths[index] > 65000) {
                widths[index] = 65000;
            }
        }
    }

    @Override
    public byte[] getBytes() throws Exception {
        // 为每一列设置宽度
        for (int index = 0; index < widths.length; ++index) {
            sheet.setColumnWidth(index, widths[index]);
        }

        //转byte数组 使用workbook.getByte[] 会出错
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        return os.toByteArray();
    }

    public XlsDataExporter() throws Exception {
        workbook = new HSSFWorkbook();
        sheet = workbook.createSheet("sheet1");
        //设置默认宽度
        sheet.setDefaultColumnWidth(200);
        cellStyle = workbook.createCellStyle();
        //左对齐
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        //cellStyle.setWrapText(true);//自动换行 不生效
    }
}
